'use strict';

const { Controller } = require('egg');
// const sendToWormhole = require('stream-wormhole');

function sliceString(str = '', key = '') {
    const firstIndex = str.indexOf(key);
    return str.slice(firstIndex + key.length);
}

class UtilsFile extends Controller {
    // 临时密钥接口
    async uploadWebKey() {
        await this.service.utilsFilesCos.sts()
            .then(res => {
                this.ctx.returnBody(200, '临时密钥获取成功', res);
                // this.ctx.body = res;
            }).catch(err => {
                this.ctx.returnBody(501, '临时密钥获取失败', err);
            });
    }
    // 配合web端直传的储存文件数据接口
    async uploadWebSave() {
        const { url, title, filename, filepath, mimetype, size } = this.ctx.request.body;
        await this.app.mysql.insert('base_files', {
            user_id: this.ctx.token.user_id,
            url: sliceString(url, '://'),
            title,
            filename,
            filepath,
            mimetype,
            size,
            delete: 1
        }).then(res => {
            this.ctx.returnBody(200, '文件数据保存成功', res.insertId);
        });
    }
    // 简单上传接口
    async uploadSimple() {
        const stream = await this.ctx.getFileStream();
        const size = stream._readableState.length;
        if (size > 10485760) {
            return this.ctx.returnBody(400, '此接口不能上传大于10M的文件');
        }
        // 调用简单上传服务
        const putObjectRes = await this.service.utilsFilesCos.putObject({ stream });

        // 把文件信息存入数据库中
        await this.app.mysql.insert('base_files', {
            user_id: this.ctx.token.user_id,
            url: putObjectRes.Location,
            title: stream.fieldname,
            filename: stream.filename,
            mimetype: stream.mimeType,
            size
        }).then(_ => {
            this.ctx.returnBody(200, '上传成功', putObjectRes.Location);
        }).catch(_ => {
            this.ctx.returnBody(500, '上传失败, 检查数据库');
        });
    }
    // 删除文件接口
    async destroy() {
        const { id } = this.ctx.params;
        const { affectedRows } = await this.app.mysql.update('base_files', { delete: 1 }, { where: { id }});

        if (affectedRows !== 1) {
            return this.ctx.returnBody(200, '文件不存在');
        }
        this.ctx.returnBody(200, '文件删除成功');
    }
}

module.exports = UtilsFile;
